import {http} from "~/icesoft/utils/request/request";
import {HttpService, JsonResult} from "~/icesoft/utils/request/types";
import {CryptHelper} from "~/icesoft/utils/service/CryptHelper";
import {AttachMore} from "~/icesoft/utils/service/types";
import {useUserStore} from "~/store/modulers/user";
import {reactive} from "vue";
import {message} from "ant-design-vue";

export class BaseApi<T> {

    baseUrl: string = '';

    http: HttpService = http;

    smsState = reactive({
        loading: false,
        msg: "发送短信验证码",
        timing: 60,
    });

    constructor() {
        this.getPublicKey();
    }

    async getPublicKey() {
        let publicKey = window.localStorage.getItem("public");
        if (!publicKey) {
            const res = await this.http.get("/auth/getPublicKey", {}, false);
            if (res.data && res.ok) {
                window.localStorage.setItem("public", JSON.stringify(res.data));
                publicKey = window.localStorage.getItem("public");
            }
        }
        return publicKey;
    }

    async safeRequest<T>(url: string, data?: any): Promise<JsonResult> {
        const publicIdKey = await this.getPublicKey();
        const {keyId, publicKey} = JSON.parse(publicIdKey as any);
        const cryptHelper = new CryptHelper(keyId, publicKey);
        const nonceStr = cryptHelper.randomKeys();
        const timeUnit = new Date().getTime().toString();

        if (!data) {
            data = {};
        }

        data = JSON.parse(JSON.stringify(data));
        data.nonceStr = nonceStr;
        data.timeUnit = timeUnit;

        const sign = cryptHelper.signData(data);
        const rsaSign = cryptHelper.rsaEncrypt(sign);

        const headers = {
            "Content-Type": "application/json;charset=utf8",
            "x-requested-with": "XMLHttpRequest",
            keyId: keyId,
            clientType: "javascript",
            versionCode: 2,
            nonceStr: nonceStr,
            timeUnit: timeUnit,
            sign: rsaSign,
        };
        const body = cryptHelper.aesEncrypt(sign, JSON.stringify(data));
        return this.http.post(url, body, {headers: headers}).then(res => {
            if (res.data != null) {
                const aesDecrypt = cryptHelper.aesDecrypt(sign, <string>res.data);
                res.data = JSON.parse(typeof aesDecrypt === "string" ? aesDecrypt : "");
            }
            return Promise.resolve(res);
        }).catch(resp => {
            return Promise.reject(resp);
        });
    }

    attachMore(params: AttachMore[]) {
        return this.http.post("/common/attachMore", params);
    }

    attachMoreFilter(attachMoreDTO: AttachMore, parentValue?: string, parentType?: string) {
        return this.http.post("/common/attachMoreFilter", {
            attachMoreDTO: attachMoreDTO,
            parentValue: parentValue,
            parentType: parentType,
        });
    }

    getUserInfo() {
        const userStore = useUserStore();
        return userStore.user;
    }

    getToken() {
        return window.localStorage.getItem("token");
    }

    downLoadZip(url: string) {
        this.http.get("/api" + this.baseUrl + url, {
            responseType: "blob",
            headers: {"Authorization": "Bearer " + this.getToken()},
        }).then((response: any) => {
            let blob = new Blob([response.data]);
            const name = "downLoad.zip";
            const elink: any = document.createElement("a");
            elink.download = name;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            // 释放URL对象
            URL.revokeObjectURL(elink.href);
            document.body.removeChild(elink);
        });
    }

    sendSmsCode(phone: string) {
        if (this.smsState.timing != 60) {
            return false;
        }
        if (!phone || phone.length == 0) {
            message.error("请输入手机号");
            return false;
        }
        this.smsState.loading = true;
        this.http.get("/auth/sendSmsCode", {params: {phone: phone}}).then(res => {
            if (res.ok) {
                message.success("发送成功，请注意查看手机短信");
                setTime();
            }
        }).finally(() => {
            this.smsState.loading = false;
        });

        const _this = this;

        function setTime() {
            if (_this.smsState.timing === 0) {
                _this.smsState.timing = 60;
                _this.smsState.msg = "发送短信验证码";
            } else {
                _this.smsState.timing--;
                _this.smsState.msg = `${_this.smsState.timing}s 后可重新发送`;
                setTimeout(function () {
                    setTime();
                }, 1000);
            }
        }
    }
}
